package com.moodbox.server.common.interceptor;

import com.moodbox.server.common.annotation.RequireRole;
import com.moodbox.server.common.enums.UserRoleEnum;
import com.moodbox.server.common.exception.AuthorizationException;
import com.moodbox.server.user.entity.User;
import com.moodbox.server.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
@RequiredArgsConstructor
public class RoleAuthInterceptor implements HandlerInterceptor {

    private final UserService userService;

    @Override
    public boolean preHandle(
        HttpServletRequest request, 
        HttpServletResponse response, 
        Object handler
    ) throws Exception {
        // 非方法直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequireRole requireRole = handlerMethod.getMethodAnnotation(RequireRole.class);

        // 没有注解，不需要权限验证
        if (requireRole == null) {
            return true;
        }

        // 获取用户ID（假设通过Authorization头传递）
        String userId = request.getHeader("Authorization");
        if (userId == null) {
            throw new AuthorizationException("未提供用户认证信息");
        }

        // 获取用户信息
        User user = userService.getUserById(userId);
        if (user == null) {
            throw new AuthorizationException("用户不存在");
        }

        // 获取用户角色
        UserRoleEnum userRole = UserRoleEnum.getByCode(user.getRole());

        // 权限验证
        if (requireRole.strict()) {
            // 严格匹配
            if (userRole != requireRole.value()) {
                throw new AuthorizationException("权限不足");
            }
        } else {
            // 最小权限匹配
            if (userRole.getCode() < requireRole.value().getCode()) {
                throw new AuthorizationException("权限不足");
            }
        }

        log.info("用户{}通过权限验证", userId);
        return true;
    }
} 